using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TeamTime.Classes;
using StillVoiceCommon;
namespace TeamTime
{
    public partial class TimeEntriesForm : System.Web.UI.Page //TeamTime.Classes.CompressedPage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //Companies companies = new Companies();

                // this.txtFromDate.Text = DateTime.Now.AddDays(-7).ToString("yyyy/MM/dd"); //default to 1 weeks worth of Batches
                //GridView1.Attributes.Add("SortExpression", "ContactDate desc");
                //GridView1.Attributes.Add("SortExpression", "ID");

                ViewState["SortExpression"] = "StartDateTime"; ViewState["SortDirection"] = "asc";
                //GridView1_Sorting(null,null);

                if (Request.QueryString["TaskID"] != null)
                {

                    string TaskID = Request.QueryString["TaskID"];
                    TimeEntryFormControl1.TaskID = Convert.ToInt32(TaskID);
                    popUp1.Show();
                }

                else if (Functions.IsNumeric(Request.QueryString["ID"]))
                {
                    this.TimeEntryFormControl1.TimeEntryID= Convert.ToInt32(Request.QueryString["ID"]);
                    this.txtSearchFor.Text = this.TimeEntryFormControl1.TimeEntryID.ToString();
                    popUp1.Show();
                }
                //else if (Request.QueryString["CompanyID"] != null)
                //{
                //    this.ContactRecordFormControl1.
                //}

                //if (Functions.IsNumeric(Request.QueryString["CompanyID"]))
                //{
                //    Companies companies = new Companies();
                //    this.txtCompanyNameSearch.Text = companies.getCompanyNameByID(Convert.ToInt32(Request.QueryString["CompanyID"]));
                //}

                EnableControls();
                DateTime dt = DateTime.Today.AddDays(-1 * (DateTime.Today.Day - 1));
                this.txtFromDate.Text = dt.AddMonths(0).ToString("yyyy/MM/dd"); // First day of last month
                DateTime month = dt.AddMonths(1);
                TN5YProjects tn5yproject = new TN5YProjects();
                Functions.dropDownListPopulate(this.ddlProjectIdFilter, tn5yproject.getProjects(true), "ID", "CompanyProject");

                StaffMembers staffMembers = new StaffMembers();

                Functions.dropDownListPopulate(this.ddlStaffMemberID, staffMembers.getStaffMembers(true), "ID", "FullName");

                Users user = new Users();
                Int32 PersonID = user.getPersonIDFromUser(Session["UserID"].ToString());
                ddlStaffMemberID.SelectedValue = Convert.ToString(user.getIDFromViewStaffMembers(PersonID));
                this.txtToDate.Text = month.AddDays(-1).ToString("yyyy/MM/dd"); // Last day of last month
                btnSearch_Click(sender, e);
                this.Form.DefaultFocus = this.txtSearchFor.ClientID;
                this.Form.DefaultButton = this.btnSearch.UniqueID;

            }

        }

        private void EnableControls()
        {

            Functions.enableChildControls(this.Form);

        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        public DateTime fromdate;
        public DateTime todate;
        
        private void BindGrid()
        {

            TimeEntries tasks = new TimeEntries();
            if (txtFromDate.Text == string.Empty)
            {
                fromdate = Convert.ToDateTime("1999-09-09");
            }
            else { fromdate = Convert.ToDateTime(txtFromDate.Text); }
            if (txtToDate.Text == string.Empty)
            {
                todate = Convert.ToDateTime("3000-03-03");
            }
            else { todate = Convert.ToDateTime(txtToDate.Text); }
            this.GridView1.DataSource = tasks.search(this.txtSearchFor.Text, fromdate,
                 todate, chkSearchDetails.Checked, Convert.ToInt32(this.ddlProjectIdFilter.SelectedValue),
                 Convert.ToInt32(this.ddlStaffMemberID.SelectedValue), ViewState["SortExpression"] + " " + ViewState["SortDirection"]
                 , this.ddlStatusFilter.SelectedValue);


            this.GridView1.DataBind();
            decimal tot = 0;
            if (GridView1.Rows.Count > 0)
            {
                foreach (GridViewRow r in GridView1.Rows)
                {
                    tot += Convert.ToDecimal(((Label)r.FindControl("lblHours")).Text);
                }
                ((Label)this.GridView1.HeaderRow.FindControl("lblTotalHours")).Text = tot.ToString("0.00");
            }


        }
        
        protected void chkCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            bool checkAll = ((CheckBox)this.GridView1.HeaderRow.FindControl("chkCheckAll")).Checked;
            foreach (GridViewRow r in this.GridView1.Rows)
            {
                ((CheckBox)r.FindControl("chkID")).Checked = checkAll;
            }
        }

        public string getSumOfDuration(DataSet val)
        {
            decimal? total = 0;
            foreach (DataRow dr in val.Tables[0].Rows)
            {
                total = (total + (decimal?)dr["Duration"]);
            }
            if (total == null)
            {
                total = 0;
                return total.ToString();
            }
            else
            {
                return total.ToString();
            }

        }


        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            TimeEntryFormControl1.setForAdding();

            //if (this.txtCompanyNameSearch.Text != "")
            //    ((TextBox)this.TimeEntryFormControl1.FindControl("txtCompanyName")).Text = this.txtCompanyNameSearch.Text;
            //popUp1.Attributes.Add("btnAddClick", "clicked");
            popUp1.Show();

        }


        protected void ContactRecordFormControl1_LoadDupClicked(object sender, EventArgs e)
        {
            popUp1.Show();
        }


        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                string id = e.CommandArgument.ToString();
                TimeEntryFormControl1.TimeEntryID = Convert.ToInt32(id);
                popUp1.Show();
            }
        }
        
        protected void btnInvoice_Click(object sender, EventArgs e)
        {
            if (this.txtInvoice.Text != "")
            {
                GridViewRow r;
                TimeEntry timeEntry = new TimeEntry();
                for (int i = 0; i < GridView1.DataKeys.Count; i++)

                //foreach (GridViewRow r in this.GridView1.Rows)
                {
                    int ID = Convert.ToInt32(GridView1.DataKeys[i][0]);
                    r = GridView1.Rows[i];
                    if (((CheckBox)r.FindControl("chkID")).Checked)
                    {
                        timeEntry.load(ID);
                        timeEntry.Fields["InvoiceNumber"] = this.txtInvoice.Text;
                        timeEntry.UserIDModifiedBy = Convert.ToInt32(Session["UserID"]);
                        timeEntry.updateWithUserIDDate();
                    }
                }
            }
            BindGrid();
        }
        
        protected void TimeEntryFormControl1_SaveClicked(object sender, EventArgs e)
        {
            popUp1.Show();
            BindGrid();
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            ViewState["SortDirection"] = Functions.getSortDirection(ViewState["SortExpression"].ToString(),
                                                 e.SortExpression, ViewState["SortDirection"].ToString());
            ViewState["SortExpression"] = e.SortExpression;

            GridView1.Attributes.Add("SortExpression", e.SortExpression);
            BindGrid();
        }
        
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView theGrid = sender as GridView;  // refer to the GridView
            int newPageIndex = 0;

            if (-2 == e.NewPageIndex)
            { // when click the "GO" Button
                TextBox txtNewPageIndex = null;
                //GridViewRow pagerRow = theGrid.Controls[0].Controls[theGrid.Controls[0].Controls.Count - 1] as GridViewRow; // refer to PagerTemplate
                GridViewRow pagerRow = theGrid.BottomPagerRow; //


                if (null != pagerRow)
                {
                    txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox;   // refer to the TextBox with the NewPageIndex value
                }

                if (null != txtNewPageIndex)
                {
                    newPageIndex = int.Parse(txtNewPageIndex.Text) - 1; // get the NewPageIndex
                }
            }
            else
            {  // when click the first, last, previous and next Button
                newPageIndex = e.NewPageIndex;
            }

            // check to prevent form the NewPageIndex out of the range
            newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
            newPageIndex = newPageIndex >= theGrid.PageCount ? theGrid.PageCount - 1 : newPageIndex;

            // specify the NewPageIndex
            theGrid.PageIndex = newPageIndex;

            // display a new page of data
            // GridView1.EditIndex = -1;
            //GridView1.PageIndex = e.NewPageIndex;
            BindGrid();
            // rebind the control
            // in this case of retrieving the data using the xxxDataSoucr control,
            // just do nothing, because the asp.net engine binds the data automatically
        }

        protected string formatNum(object fld)
        {
            if (fld == DBNull.Value)
            {
                return "";

            }
            else
            {
                return Convert.ToDecimal(fld).ToString("0.00");
            }


        }


    }


}



